/* eslint-disable */
import { openFakeWin, sendSbList, logout } from "./tool.js";
import { insertMoment, nextTick } from "../../lib/utils.js";
import { zeroCwbbReprot } from './cwbbReport.js';
import {
  handleSmallIndex,
  tableMainSave1,
  handleSmallStep1,
  handleSmallStep2,
  handleSmallStep3,
} from "./smallZeroReport.js";
import {
  getQysdsLi,
  qysdsReprotQ,
  qysdsReprot,
  qysdsReprotTable,
  qysdsReprotQuery,
} from "./qysds.js";
import { asyncSetInterval, fixZeroInfo, notifications, closeTabs } from "../../lib/zeroReportUtils.js";

let currentZeroInfo;
const pages = {
  index: "etax.chongqing.chinatax.gov.cn/sword",
  step1:
    "etax.chongqing.chinatax.gov.cn:8001/WLSB/WLSBBS/TTAX_index.html?MODULE=TTAX_WBZR.html",
  step2: "etax.chongqing.chinatax.gov.cn:6011/sword?ctrl=SB246FjsfnssbCtrl_initView",
  step3:
    "etax.chongqing.chinatax.gov.cn:8001/WLSB/WLSBBS/TTAX_index.html?MODULE=TTAX_SB_JCSB.html",
  // 企业所得税需要打开的网页
  step20:
    "wbjr.chongqing.chinatax.gov.cn/PortalWeb/pages/qysds/qysdsIndexNew.html",
  step21:
    "wbjr.chongqing.chinatax.gov.cn:8888/sbzx-web/apps/views/sb_sdsA_yj_new_202006/sb_sdsA_yj_new.html",
  step22:
    "wbjr.chongqing.chinatax.gov.cn:8888/sbzx-web/apps/views/sbjgcx/sbjgcx.html",
  step23:
    "etax.chongqing.chinatax.gov.cn/sword?ctrl=WBLoginGdgjCtrl_openSecondWin",
  cwbbPage1: 
    'etax.chongqing.chinatax.gov.cn:6011/sword?ctrl=SB151zlbsslCtrl_initView'
};

const isPage = (name) => {
  return window.location.href.includes(pages[name]);
};

const cesiStatus = (currentZeroInfo) => {
    let backInfo = {
      ...currentZeroInfo,
      recordList: [
        {
          declareName: '报表pdf',
          declareCycle: 'month',
          accountBook: '2020-04',
          isSuccess: true,
        }
      ],
    };
    // 零申报结束
    window.postMessage(
      {
        event: 'zeroReportBack',
        data: backInfo,
      },
      '*'
    );
}

const cesiTable = () => {
  let tableContent = {
    declareType: '报表pdf',
    title: '这是一个url',
    // html: '<div>helloworld</div>',
    // css: ''
    url: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1590745832895&di=324550e26ac05b77cdb74836f29c4fef&imgtype=0&src=http%3A%2F%2Fa4.att.hudong.com%2F58%2F27%2F01300000290906122849276486503.jpg'
  }
  window.postMessage(
    {
      event: 'asyncTableDetail',
      data: tableContent
    },
    '*'
  );
  setTimeout(() => {
    window.postMessage({
      event: 'asyncTableDetailRequest'
    }, "*")  
  }, 1000);
}

const startZeroReport = async (data) => {
  if (window.location.href === "https://etax.chongqing.chinatax.gov.cn/") {
    handleLogin(data.data.currentZeroInfo);
    window.sessionStorage.setItem("isZero", true);
    window.sessionStorage.setItem("zeroStep", 1);
  }
  currentZeroInfo = data.data.currentZeroInfo;
  
  // 测试同步申报表
  // cesiStatus(data.data.currentZeroInfo);
  // 测试同步变明细
  // setTimeout(() => {
  //   cesiTable();
  // }, 2000);
};

const handleLogin = (info) => {
  console.log(info);
  if (info.zzsType === "小规模纳税人") {
    window.sessionStorage.setItem("isSmall", true);
  }
  $(".alert_click_show").click();
  nextTick(() => {
    $('.alert_click_show').click();
    $('#shxydm_qy').val(info.nationalTaxNo);
    $('#username_qy').val(info.nationalTaxUser);
    $('#password_qy').val(info.nationalTaxPass);
    return true;
  }, 300);
};

const handleIndex = () => {
  openFakeWin('null', 'F251000200000176','按期申报套餐','102230');
  closeTabs(1000);
};

function openSecondWin(CygnBZ,fqxDm, fqxMc, qxDm, qxMc) {
  window.open("sword?ctrl=WBLoginGdgjCtrl_openSecondWin&CygnBZ="+CygnBZ+"&qxDm=" + qxDm + "&fqxDm=" + fqxDm + "&fqxMc=" + encodeURI(encodeURI(fqxMc)) + "&qxMc=" + encodeURI(encodeURI(qxMc)));
}

const cwbbBtnClick = async (cwbb) => {
  let btn = Array.from($(cwbb[7]).find('a')).find(item => $(item).text().includes('填写财报'));
  console.log(btn);
  if(btn) {
    btn.click();
    asyncSetInterval(() => {
      let sureBtn = document.querySelector("body .ui_buttons input.ui_state_highlight");
      if(sureBtn)  {
        sureBtn.click();
        closeTabs(1000);
        return true;
      }
    }, 1000)
  } else {
    let cwbbItem = recordList.find(item => item.declareName.includes('财务报表资料报送与采集'));
    cwbbItem.isSuccess = true;
    fixZeroInfo({ recordList: cwbbItem });
    window.location.reload();
  }
}

const handleStep3 = (currentZeroInfo) => {
  insertMoment();
  let bizContent = null;
  let tdList = [];
  return asyncSetInterval( () => {
    let indexContent = $('#indexContent');
    if(indexContent.length && indexContent.contents().find('#bizContent').length) {
      bizContent = indexContent.contents().find('#bizContent');
      return true;
    }
  }, 1000).then(() => {
    return asyncSetInterval(() => {
      let trs = bizContent.contents().find('.datagrid-body table tr');
      let mark = bizContent.contents().find('#ts_xt > div.blockUI.blockOverlay');
      if(trs.length && mark.length === 0) {
        let sbAllList = Array.from(trs).map(item => {
          let tds = Array.from($(item).find("td")).filter(td => {
            return $(td).css('display') !== 'none';
          });
          tdList.push(tds);
          let month = currentZeroInfo.endPeriod >= 10 ? currentZeroInfo.endPeriod : `0${currentZeroInfo.endPeriod}`;
          let declareCycle = 0;
          if($(tds[1]).text().includes('财务报表资料报送与采集')) {
            let kssj = $(tds[3]).text().split('-')[1];
            let jssj = $(tds[4]).text().split('-')[1];
            let jk = parseInt(jssj)-parseInt(kssj);
            month = jssj;
            declareCycle = jk === 11 ? 'year' : (jk === 2 ? 'season' : 'month');
          } else {
            try {
              let kssj = $(tds[3]).text().split('~')[0].split('-')[1];
              let jssj = $(tds[3]).text().split('~')[1].split('-')[1];
              let jk = parseInt(jssj)-parseInt(kssj);
              month = jssj;  
            } catch (e) {
              console.log(e);
            }
            declareCycle = $(tds[2]).text() === '年报' ? 'year' : ($(tds[2]).text() === '季报' ? 'season' : 'month')
          }
          return {
            declareName: $(tds[1]).text().trim(),
            declareCycle,
            accountBook:currentZeroInfo.year + '-' + month,
            isSuccess: $(tds[7]).text().includes('已申报') || $(tds[5]).text().includes('已报送'),
          }
        });
        if (sbAllList.length > currentZeroInfo.recordList.length) {
          fixZeroInfo({recordList: sbAllList});
          window.onbeforeunload = null;
          window.location.reload();
        } else {
          return sbAllList;
        }
      }
    }, 1000)
  }).then(sbAllList => {
      console.log(sbAllList);
      let {recordList, customerType} = currentZeroInfo;
      if(!recordList || recordList.length ===0 ) {
        recordList = [...sbAllList];
      }
      // 财务报表  只支持小企业会计准则 customerType = 小企业会计准则
      let cwbbItem = recordList.find(item => item.declareName.includes('财务报表资料报送与采集'));
      let isXqykjzz = customerType.includes('小企业会计准则');
      if(isXqykjzz) notifications('暂时不支持企业会计准则自动零申报');
      if(cwbbItem && !cwbbItem.isSuccess && isXqykjzz) {
        let cwbb = Array.from(tdList).find((item) => $(item[1]).text() === "财务报表资料报送与采集");
        cwbbBtnClick(cwbb, recordList);
        return true;
      }
      // 增值税
      let zzsItme = recordList.find(item => item.declareName.includes('增值税'));
      if(zzsItme && !zzsItme.isSuccess) {
        let zzs = Array.from(tdList).find((item) => $(item[1]).text() === "增值税");
        if($(zzs[7]).text().includes('已申报')) {
          fixZeroInfo({recordList: sbAllList});
          setTimeout(() => {
            window.location.reload();
          }, 1000);
        } else {
          $(zzs[8]).find('a').click();
          asyncSetInterval(() => {
            let input = document.querySelector("body table.ui_border.ui_state_focus div.ui_buttons input[type=button].ui_state_highlight");
            if(input) {
              input.click();
              return true;
            }
          }, 1000).then(() => {
            return asyncSetInterval(() => {
              let indexContent = $("#indexContent"); 
              if(indexContent.length && !indexContent.contents().find("#ts_xt > div.blockUI.blockOverlay").length) {
                  if(currentZeroInfo.zzsType === "小规模纳税人") {
                    let win=$("#indexContent")[0].contentWindow;
                    tableMainSave1(win, currentZeroInfo);
                  } else {
                    table2save();
                  }
                  return true;
              }
            }, 5000);
          });  
        }
        return true;
      }
      // 附加税
      let fjsItme = recordList.find(item => item.declareName.includes('附加税（费）申报'));
      if(fjsItme && !fjsItme.isSuccess) {
        let fjs = Array.from(tdList).find((item) => $(item[1]).text() === "附加税（费）申报");
        if($(fjs[7]).text().includes('已申报')) {
          fixZeroInfo({recordList: sbAllList});
          setTimeout(() => {
            window.location.reload();
          }, 1000);
          return true;
        }
        $(fjs[8]).find('a').click();
        setTimeout(()=> {window.close()}, 1000);
        return true;
      }
      // 企业所得税
      let qysdsItme = recordList.find(item => item.declareName.includes('企业所得税'));
      if(qysdsItme && !qysdsItme.isSuccess) {
        let qysds = Array.from(tdList).find((item) => $(item[1]).text() === "企业所得税");
        if($(qysds[7]).text().includes('已申报')) {
          fixZeroInfo({recordList: sbAllList});
          setTimeout(() => {
            window.location.reload();
          }, 1000);
          return true;
        }
        $(qysds[8]).find('a').click();
        setTimeout(()=> {window.close()}, 1000);
      }
      window.postMessage(
        {
          event: 'zeroReportBack',
          data: {...currentZeroInfo},
        },
        '*'
      );
  })
};

const handleStep2 = () => {
  nextTick(() => {
    let btns = document.getElementsByClassName("submit_ie67_btn");
    if (btns && btns.length && btns[1]) {
      btns[1].click();
      nextTick(() => {
        let yesBtn = document.getElementById("ymPrompt_btn_0");
        if (yesBtn) {
          yesBtn.click();
          window.setTimeout(() => {
            let el = document.getElementsByClassName("ym-content");
            if (el.length && el[0].innerText.includes("保存成功")) {
              let recordList = currentZeroInfo.recordList;
              let fjs = recordList.find(item => item.declareName.includes('附加税'));
              fjs.isSuccess = true;
              fixZeroInfo({recordList: [fjs]});
              setTimeout(() => {
                window.location.href = 'https://etax.chongqing.chinatax.gov.cn/sword?ctrl=WBLoginGdgjCtrl_openLayout3Win';
              }, 1000);
            }
          }, 2000);
          return true;
        }
      }, 1000);
      return true;
    }
  }, 8000);
};

const handleStep1 = () => {
  nextTick(() => {
    if ($("table.ui_state_focus .ui_state_highlight").length) {
      if ($("table.ui_state_focus .ui_state_highlight").val() === "填表申报") {
        $("table.ui_state_focus .ui_state_highlight").click();
        setTimeout(() => {
          if($('body > div.model > div > div.model_footer > input').length) {
            $('body > div.model > div > div.model_footer > input').click();
          }  
          table2save();
        }, 500);
        return true;
      } else {
        setTimeout(() => {
          window.location.reload();
        }, 3000);
      }
    }
  });
};

const table2save = () => {
  setTimeout(() => {
    let opents = $("[name='OpenTS']")[0];
    if (opents && opents.contentWindow && opents.contentWindow.uf_setNoTips) {
      opents.contentWindow.uf_setNoTips();
    }
    nextTick(() => {
      let win = $("#indexContent")[0].contentWindow;
      let table2btn = win.$(
        "#datagrid-row-r2-2-2 td[field='BB_MC'] .datagrid-cell"
      );
      console.log(table2btn);
      if (table2btn) {
        table2btn.click();
        setTimeout(() => {
          table2btn.dblclick();
          nextTick(() => {
            if (!$(".blockOverlay").length) {
              win.$("#return_save").click();
              nextTick(() => {
                if (
                  $(".ui_state_highlight").length &&
                  $(".ui_state_highlight").val() === "确定"
                ) {
                  $(".ui_state_highlight").click();
                  table1save(win);
                  return true;
                }
              });
              return true;
            }
          }, 500);
        }, 500);
        return true;
      }
    }, 1000);
  }, 5000);
};

const table1save = (win) => {
  nextTick(() => {
    let table1btn = win.$(
      "#datagrid-row-r2-2-1 td[field='BB_MC'] .datagrid-cell"
    );
    if (table1btn) {
      table1btn.click();
      setTimeout(() => {
        table1btn.dblclick();
        nextTick(() => {
          if (!$(".blockOverlay").length) {
            win.$("#return_save").click();
            nextTick(() => {
              if (
                $(".ui_state_highlight").length &&
                $(".ui_state_highlight").val() === "确定"
              ) {
                $(".ui_state_highlight").click();
                tableMainSave(win);
                return true;
              }
            });
            return true;
          }
        }, 500);
      }, 500);
      return true;
    }
  }, 1000);
};

const startShenbao = () => {
  if (
    $(".ui_state_lock .ui_state_highlight").length &&
    $(".ui_state_lock .ui_state_highlight").val() === "确定"
  ) {
    $(".ui_state_lock .ui_state_highlight").click();
    nextTick(() => {
      if (
        $(".ui_state_full iframe").length &&
        $(".ui_state_full iframe").contents().find("#fullResult").length
      ) {
        if (
          $(".ui_state_full iframe")
            .contents()
            .find("#fullResult")
            .html()
            .includes("申报已经成功")
        ) {
          // 结束申报
          let recordList = currentZeroInfo.recordList;
          let zzsItme = recordList.find(item => item.declareName.includes('增值税'));
          zzsItme.isSuccess = true;
          fixZeroInfo({recordList: [zzsItme]});
          setTimeout(() => {
            window.location.reload();
          }, 1000);
        }
        return true;
      }
    }, 15000);
  }
};

const tableMainSave = (win) => {
  nextTick(() => {
    let table0btn = win.$(
      "#datagrid-row-r2-2-0 td[field='BB_MC'] .datagrid-cell"
    );
    if (table0btn) {
      table0btn.click();
      setTimeout(() => {
        table0btn.dblclick();
        nextTick(() => {
          if (!$(".blockOverlay").length) {
            win.$("#return_save").click();
            nextTick(() => {
              if (
                $(".ui_state_highlight").length &&
                $(".ui_state_highlight").val() === "确定"
              ) {
                $(".ui_state_highlight").click();
                setTimeout(() => {
                  win.$("#return_sb").click();
                  nextTick(() => {
                    if (
                      $(".ui_state_lock .ui_state_highlight").length &&
                      $(".ui_state_lock .ui_state_highlight").val() === "确定"
                    ) {
                      if (
                        $(".ui_state_lock .ui_content span:eq(0)").length &&
                        $(".ui_state_lock .ui_content span:eq(0)").html() ===
                          "抄报税"
                      ) {
                        $(".ui_state_lock .ui_state_highlight").click();
                        setTimeout(() => {
                          startShenbao();
                        }, 1000);
                      } else {
                        startShenbao();
                      }
                      return true;
                    }
                  }, 2000);
                }, 1000);
                return true;
              }
            });
            return true;
          }
        }, 500);
      }, 500);
      return true;
    }
  }, 1000);
};

const checkZeroReport = () => {
  nextTick(() => {
    if (currentZeroInfo) {
      // index 操作
      if (isPage("index") && window.location.href.includes('WBLoginGdgjCtrl_openLayout3Win')) {
        handleIndex();
        return true;
      }
      // 财务报表
      if (isPage('cwbbPage1')) {
        zeroCwbbReprot(currentZeroInfo);
      }
      // 一般纳税人增值税 and 小规模增值税
      if (isPage("step1")) {
        if(currentZeroInfo.zzsType === "小规模纳税人") {
          // handleSmallStep1();
        } else {
          // handleStep1();
        }
        return true;
      }
      // 附加税
      if(isPage('step2')){
        handleStep2();
        return true;
      }

      // 企业所得税前置
      if (isPage("step23")) {
        qysdsReprotQ(currentZeroInfo);
        return true;
      }
      if (isPage("step20")) {
        qysdsReprot(currentZeroInfo);
        return true;
      }
      // 企业所得税申报
      if (isPage("step21")) {
        qysdsReprotTable(currentZeroInfo);
        return true;
      }
      // 企业所得税查询
      if (isPage("step22")) {
        qysdsReprotQuery(currentZeroInfo);
        return true;
      }
      
      // 应申报页面
      if (isPage('step3')) {
        let zeroReport = window.sessionStorage.getItem('zeroReport');
        if(parseInt(zeroReport) !== 1) {
          handleStep3(currentZeroInfo);
        }
      }
      return true;
    }
  });
};

export { startZeroReport, checkZeroReport };
